package com.gitee.wsl.doc.prosemirror.model.content.ext

import com.gitee.wsl.doc.prosemirror.model.content.ResolvedPos


/**
 * 在指定位置后查找可切割的位置
 * @param pos 解析位置对象
 * @return 可切割位置或null
 */
fun ResolvedPos.findCutAfter(): ResolvedPos? {
    val pos = this
    // 如果父节点不是隔离类型，则向上遍历
    if (pos.parent.type.spec.isolating!=true) {
        for (i in pos.depth - 1 downTo 0) {
            val parent = pos.node(i)

            // 检查当前索引是否小于父节点的子节点数量
            if (pos.index(i) + 1 < parent.childCount) {
                return pos.doc.resolve(pos.after(i + 1))
            }

            // 如果父节点是隔离类型，则停止遍历
            if (parent.type.spec.isolating == true) {
                break
            }
        }
    }
    return null
}

fun ResolvedPos.findCutBefore(): ResolvedPos? {
    val pos = this
    if (pos.parent.type.spec.isolating != null)
        ((pos.depth - 1) ..0).forEach{i->
            if (pos.index(i) > 0) return pos.doc.resolve(pos.before(i + 1))
            if (pos.node(i).type.spec.isolating == true) return null
        }
    return null
}